package com.codeying.controller;

import com.codeying.component.excel.ExcelLogs;
import com.codeying.component.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.codeying.utils.component.*;
import com.codeying.utils.*;
import com.codeying.entity.*;
import com.codeying.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.io.InputStream;
import java.util.*;
import java.io.File;
import java.io.IOException;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.FileUtils;
import jakarta.servlet.ServletOutputStream;
/** 系统公告功能 关于系统公告增删改查等 */
@Controller
@RequestMapping({"notice"})
public class NoticeController extends BaseController {

  /**
   * 系统公告列表页
   *
   * @param model
   * @param pageIndex
   * @param orderby
   * @return
   */
  @RequestMapping("list")
  public String list(Model model, Integer pageIndex, String[] orderby) {
    if (pageIndex == null) {
      pageIndex = 1; // 默认访问系统公告第一页,分页
    }

    IPage<Notice> pageInfo = new Page<Notice>().setCurrent(pageIndex).setSize(15); // 分页大小
    // 获取系统公告列表数据
    QueryWrapper<Notice> queryWrapper = getQueryWrapper(orderby);

    // 使用原始系统公告queryWrapper进行分页查询（未被修改select条件）
    pageInfo = noticeService.page(pageInfo, queryWrapper);
    // 获取到的系统公告
    List<Notice> noticeList = pageInfo.getRecords();

    // 将数据放入request

    model.addAttribute("noticeList", noticeList);
    // 将分页信息传回前端
    PagerVO pager =
        new PagerVO(
            (int) pageInfo.getCurrent(), (int) pageInfo.getSize(), (int) pageInfo.getTotal());
    model.addAttribute("pager", pager);
    return "/pages/notice-list";
  }

  /**
   * 获取查询条件
   *
   * @param orderby
   * @return
   */
  private QueryWrapper<Notice> getQueryWrapper(String[] orderby) {
    // 用于存储查询的条件
    QueryWrapper<Notice> paramMap = new QueryWrapper<>();
    String title = req.getParameter("title");
    if (!StringUtils.isEmpty(title)) {
      paramMap.like("title", title);
      req.setAttribute("title", title);
    }
    String createtimeL = req.getParameter("createtimeL");
    String createtimeR = req.getParameter("createtimeR");
    if (!StringUtils.isEmpty(createtimeL)) {
      paramMap.ge("createtime", DateUtil.strToDate(createtimeL));
      req.setAttribute("createtimeL", createtimeL);
    }
    if (!StringUtils.isEmpty(createtimeR)) {
      paramMap.le("createtime", DateUtil.strToDate(createtimeR));
      req.setAttribute("createtimeR", createtimeR);
    }

    String orderByStr = "id desc"; // 默认根据id降序排序
    if (orderby != null && orderby.length > 0) { // 如果前端传来了需要排序的字段，那么根据前端字段排序
      // 前端回显
      for (String s : orderby) {
        req.setAttribute(s.replace(" ", ""), true);
      }
      orderByStr = Arrays.toString(orderby);
      // 前端传来的排序字段都会有","开头，去掉第一个逗号
      orderByStr = orderByStr.substring(1, orderByStr.length() - 1);
    }
    // 默认按照id排序
    paramMap.last("order by " + orderByStr);
    return paramMap;
  }

  // 前往系统公告编辑页
  @RequestMapping("edit")
  public String edit(String id, Model model) {
    // 根据id获取
    Notice entity = noticeService.getById(id);
    if (entity == null) {
      entity = new Notice();
      model.addAttribute("item", entity);
      return "/pages/notice-add";
    } else {
      model.addAttribute("item", entity);
      return "/pages/notice-edit";
    }
  }

  // 系统公告详情页
  @RequestMapping("detail")
  public String detail(@RequestParam("id") String id, Model model) {
    Notice entity = noticeService.getById(id);
    model.addAttribute("item", entity);
    return "/pages/notice-detail";
  }

  // 系统公告保存
  @RequestMapping("save")
  @ResponseBody
  public ApiResult save(Notice entityTemp) {
    String id = entityTemp.getId(); // 系统公告主键
    String title = entityTemp.getTitle(); // 标题
    String content = entityTemp.getContent(); // 内容
    Date createtime = entityTemp.getCreatetime(); // 发布时间

    // 新增或更新
    if (entityTemp.getId() == null || "".equals(entityTemp.getId())) { // 新增
      id = CommonUtils.newId();
      entityTemp.setId(id);
      createtime = new Date();
      entityTemp.setCreatetime(createtime);
      // 唯一字段，则在此校验
      QueryWrapper<Notice> wrappertitle = new QueryWrapper();
      wrappertitle.eq("title", entityTemp.getTitle());
      if (noticeService.list(wrappertitle).size() > 0) {
        return fail("标题 已存在！");
      }
      // before add

      noticeService.save(entityTemp);
    } else {
      // before edit

      noticeService.updateById(entityTemp);
    }
    return ApiResult.successMsg("操作成功"); // 返回成功
  }

  // 系统公告删除
  @RequestMapping("delete")
  @ResponseBody
  public ApiResult delete(String id) {
    Notice delTemp = noticeService.getById(id);
    // before del

    // 根据ID删除记录
    noticeService.removeById(id);
    return success();
  }

  // 从excel导入数据
  @PostMapping("excel")
  @ResponseBody
  public ApiResult importexcel(@RequestParam(value = "excel") MultipartFile excel)
      throws IOException {
    if (excel != null) {
      try {
        InputStream inputStream = excel.getInputStream();
        Collection<Map> importExcel =
            ExcelUtil.importExcel(
                Map.class, inputStream, "yyyy年MM月dd日 HH:mm:ss", new ExcelLogs(), 0);
        List<Notice> list = new ArrayList<>();
        for (Map m : importExcel) {
          Notice entity = new Notice();
          entity.setId(CommonUtils.newId());
          entity.setTitle((String) m.get("标题"));
          entity.setContent((String) m.get("内容"));
          entity.setCreatetime(DateUtil.strToDate((String) m.get("发布时间"))); // 时间
          list.add(entity);
        }
        noticeService.saveBatch(list);
        return ApiResult.successMsg("导入成功");
      } catch (Exception e) {
        e.printStackTrace();
        return ApiResult.fail("文件解析失败,请检查内容是否正确！");
      }
    } else {
      return (ApiResult.fail("请选择文件"));
    }
  }

  // 导出excel
  @RequestMapping("excel")
  public void excel() throws IOException {
    // 获取数据
    List<Notice> data = noticeService.list(getQueryWrapper(null));
    // 循环遍历list数据，统计、获取外键数据
    for (Notice stAv : data) {}
    HashMap<String, String> headMap = new LinkedHashMap<>();
    headMap.put("title", "标题");
    headMap.put("content", "内容");
    headMap.put("createtime", "发布时间");
    Collection<Object> dataset = new ArrayList<>(data);
    resp.setHeader("Content-Disposition", "attachment; filename=" + "notice.xls");
    resp.setDateHeader("expries", -1);
    resp.setHeader("Cache-Control", "no-cache");
    resp.setHeader("Pragma", "no-cache");
    ServletOutputStream servletOutputStream = null;
    try {
      servletOutputStream = resp.getOutputStream();
      ExcelUtil.exportExcel(headMap, dataset, servletOutputStream);
      servletOutputStream.close();
    } catch (IOException e) {
      System.out.println("IOException");
    }
  }
}

